package com.huilan.base.esl.service.acd.domain.model;

import cn.hutool.core.util.StrUtil;
import com.huilan.base.esl.service.acd.domain.model.queue.QueueACDEnum;
import com.huilan.base.esl.service.acd.domain.model.queue.acd.IQueueACD;
import com.huilan.base.esl.service.fs.EslClient;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeansException;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;

@Component
public class Base implements ApplicationContextAware , ApplicationRunner {

    private static ApplicationContext applicationContext;

    private static RedissonClient redisson;
    private static EslClient eslClient;

    public static RedissonClient getRedisson(){
        if (redisson == null){
            redisson = getBean(RedissonClient.class,"redisson");
        }
        return redisson;
    }
    public static EslClient getEslClient(){
        if (eslClient == null){
            eslClient = getBean(EslClient.class,"eslClient");
        }
        return eslClient;
    }
    private static <T> T getBean(Class<T> t,String beanName){
        return applicationContext.getBean(beanName,t);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        for (QueueACDEnum acdEnum: QueueACDEnum.values()) {
            String acdBeanName = acdEnum.getAcdBeanName();
            if (StrUtil.isNotBlank(acdBeanName)){
                acdEnum.setIacd(getBean(IQueueACD.class,acdBeanName));
            }
        }
    }

    public static void publish (ApplicationEvent applicationEvent){
        applicationContext.publishEvent(applicationEvent);
    }

}
